/**
 * 全局进度管理器
 * 完全独立于React组件，不会触发任何重新渲染
 */

import { useDataLineageProgress } from '../hooks/useDataLineageProgress';

class GlobalProgressManager {
  private progressHooks: ReturnType<typeof useDataLineageProgress> | null = null;
  private isInitialized = false;

  // 初始化进度管理器（只在应用启动时调用一次）
  initialize(hooks: ReturnType<typeof useDataLineageProgress>) {
    if (!this.isInitialized) {
      this.progressHooks = hooks;
      this.isInitialized = true;
      console.log('🔧 GlobalProgressManager 已初始化');
    }
  }

  // 启动进度（返回通知ID）
  startProgress(dataSource: string): string | null {
    if (!this.progressHooks) {
      console.warn('⚠️ GlobalProgressManager 未初始化');
      return null;
    }
    
    try {
      const notificationId = this.progressHooks.startLineageAnalysis(dataSource);
      console.log(`📊 启动进度跟踪: ${notificationId}`);
      return notificationId;
    } catch (error) {
      console.error('❌ 启动进度失败:', error);
      return null;
    }
  }

  // 更新进度
  updateProgress(
    notificationId: string,
    progress: number,
    stage: string,
    currentItem?: string,
    statistics?: any
  ) {
    if (!this.progressHooks || !notificationId) return;
    
    try {
      this.progressHooks.updateAnalysisProgress(
        notificationId,
        progress,
        stage,
        currentItem || '',
        statistics
      );
    } catch (error) {
      console.error('❌ 更新进度失败:', error);
    }
  }

  // 完成进度
  completeProgress(
    notificationId: string,
    success: boolean,
    summary?: string,
    statistics?: any
  ) {
    if (!this.progressHooks || !notificationId) return;
    
    try {
      if (success) {
        this.progressHooks.completeAnalysis(notificationId, success, summary, statistics);
      } else {
        this.progressHooks.failAnalysis(notificationId, { message: summary || '分析失败' });
      }
      console.log(`✅ 完成进度跟踪: ${notificationId} (${success ? '成功' : '失败'})`);
    } catch (error) {
      console.error('❌ 完成进度失败:', error);
    }
  }

  // 检查是否已初始化
  isReady(): boolean {
    return this.isInitialized && this.progressHooks !== null;
  }
}

// 创建全局单例
export const globalProgressManager = new GlobalProgressManager();

// 初始化hook（只在应用根部调用一次）
export const useGlobalProgressManagerInit = () => {
  const progressHooks = useDataLineageProgress();
  
  // 只初始化一次
  if (!globalProgressManager.isReady()) {
    globalProgressManager.initialize(progressHooks);
  }
  
  return globalProgressManager;
};

// 便捷的API函数（不依赖React hooks）
export const startAnalysisProgress = (dataSource: string): string | null => {
  return globalProgressManager.startProgress(dataSource);
};

export const updateAnalysisProgress = (
  notificationId: string,
  progress: number,
  stage: string,
  currentItem?: string,
  statistics?: any
) => {
  globalProgressManager.updateProgress(notificationId, progress, stage, currentItem, statistics);
};

export const completeAnalysisProgress = (
  notificationId: string,
  success: boolean,
  summary?: string,
  statistics?: any
) => {
  globalProgressManager.completeProgress(notificationId, success, summary, statistics);
};

// 在开发环境下暴露到window对象
if (process.env.NODE_ENV === 'development') {
  (window as any).globalProgressManager = globalProgressManager;
}
